package com.ruoyi.function.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.function.constant.BusinessConstants;
import com.ruoyi.function.constant.ServiceTypeMapping;
import com.ruoyi.function.domain.Technician;
import com.ruoyi.function.domain.bo.GarageBo;
import com.ruoyi.function.service.IUserService;
import com.ruoyi.message.controller.NoticeController;
import com.ruoyi.message.notice.vo.NoticeVO;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.function.mapper.GarageMapper;
import com.ruoyi.function.domain.Garage;
import com.ruoyi.function.service.IGarageService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商户Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-18
 */
@Service
public class GarageServiceImpl implements IGarageService {
    @Autowired
    private GarageMapper garageMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private SysConfigMapper configMapper;
    @Autowired
    private NoticeController noticeController;

    /**
     * 查询商户
     *
     * @param id 商户主键
     * @return 商户
     */
    @Override
    public Garage selectGarageById(Long id) {
        Garage garage = garageMapper.selectGarageById(id);
        // 翻译 服务类型
        String s = ServiceTypeMapping.convertServiceIdsToChinese(garage.getServiceTypeIds());
        BigDecimal bigDecimal = getWorkshopLevelValue(garage.getLevel());
        garage.setServiceTypeIds(s);
        garage.setHourPrice(bigDecimal);
        return garage;
    }

    /**
     * 查询商户列表
     *
     * @param garage 商户
     * @return 商户
     */
    @Override
    public List<Garage> selectGarageList(Garage garage) {
        return garageMapper.selectGarageList(garage);
    }

    /**
     * 新增商户
     *
     * @param garage 商户
     * @return 结果
     */
    @Override
    public int insertGarage(Garage garage) {
        garage.setCreateTime(DateUtils.getNowDate());
        return garageMapper.insertGarage(garage);
    }

    /**
     * 修改商户
     *
     * @param garage 商户
     * @return 结果
     */
    @Override
    public int updateGarage(GarageBo garageBo) {

        Garage garage = new Garage();
        BeanUtils.copyProperties(garageBo, garage);
        if (garageBo.getTransportLicenses() != null) {
            garage.setTransportLicense(String.join(",", garageBo.getTransportLicenses()));
        }
        if (garageBo.getQualificationPhotosArray() != null) {
            garage.setQualificationPhotos(String.join(",", garageBo.getQualificationPhotosArray()));
        }
        if (garageBo.getShopPhotosList() != null && garageBo.getShopPhotosList().size() > 0) {
            garage.setShopPhotos(String.join(",", garageBo.getShopPhotosList()));
        }
        if (garageBo.getServiceTypeIdsArray() != null && garageBo.getServiceTypeIdsArray().length > 0) {
            garage.setServiceTypeIds(String.join(",", garageBo.getServiceTypeIdsArray()));
        }

        if (garageBo.getServiceAreasList() != null && garageBo.getServiceAreasList().size() > 0) {
            garage.setServiceAreas(String.join(",", garageBo.getServiceAreasList()));
        }
        if (garageBo.getLevel() != null){
            BigDecimal bigDecimal = getWorkshopLevelValue(garage.getLevel());
            garage.setHourPrice(bigDecimal);
        }
        garage.setAuditStatus(BusinessConstants.dict.audit_status_1);
        garage.setReceivingOrder(BusinessConstants.dict.receiving_order_0);
        garage.setUpdateTime(DateUtils.getNowDate());
//        if (garage.getStatus()==BusinessConstants.dict.status_0 && garage.getReceivingOrder()!=BusinessConstants.dict.receiving_order_0){
//            garage.setReceivingOrder(BusinessConstants.dict.receiving_order_0);
//        }

        return garageMapper.updateGarage(garage);
    }

    /**
     * 批量删除商户
     *
     * @param ids 需要删除的商户主键
     * @return 结果
     */
    @Override
    public int deleteGarageByIds(Long[] ids) {
        return garageMapper.deleteGarageByIds(ids);
    }

    /**
     * 删除商户信息
     *
     * @param id 商户主键
     * @return 结果
     */
    @Override
    public int deleteGarageById(Long id) {
        return garageMapper.deleteGarageById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int check(Garage garage) {
        Garage garage1 = garageMapper.selectGarageById(garage.getId());
        //1:只有待审核状态可以修改
        if (!BusinessConstants.dict.audit_status_1.equals(garage1.getAuditStatus())) {
            //报错
            throw new RuntimeException("只有待审核状态可以审核");
        }
        String messageContent = "";
        //同步修改用户
        Long userId = garage.getUserId();
        SysUser userById = userService.getUserById(userId);
        if (BusinessConstants.dict.audit_status_2 == garage.getAuditStatus()) {
            messageContent = BusinessConstants.message_5;

            SysUser user = new SysUser();
            user.setUserId(userId);
            //修改当前角色为商户
            user.setCurrentRole(3L);
            //修改拥有角色包含技师角色
            String roleTypes = userById.getRoleTypes();
            if (StringUtils.isNull(roleTypes)) {
                user.setRoleTypes("3");
            } else if (roleTypes.indexOf("3") == -1) {
                user.setRoleTypes(roleTypes + ",3");
            }


            userService.updateUser(user);
        } else if (BusinessConstants.dict.audit_status_3 == garage.getAuditStatus()) {
            messageContent = BusinessConstants.message_6 + garage.getAuditRemark();
        }
        BigDecimal bigDecimal = getWorkshopLevelValue(garage.getLevel());
        Garage garage2 = new Garage();
        garage2.setId(garage.getId());
        garage2.setAuditStatus(garage.getAuditStatus());
        garage2.setAuditRemark(garage.getAuditRemark());
        garage2.setHourPrice(bigDecimal);
        int i = garageMapper.updateGarage(garage2);
        if (i <= 0) {
            throw new RuntimeException("审批失败");
        }

        noticeController.sendMessage(garage.getUserId() + "", "3", messageContent);
        return i;
    }

    /**
     * 根据车间等级获取配置值
     * @param level 车间等级 (1或2)
     * @return 对应的配置值
     * @throws RuntimeException 参数无效或配置不存在时抛出
     */
    public BigDecimal getWorkshopLevelValue(Integer level) {
        // 1. 参数基础校验
        if (level == null) {
            throw new RuntimeException("车间等级不能为空");
        }

        // 2. 生成配置键
        final String configKey = buildConfigKeyByLevel(level);

        // 3. 查询配置
        SysConfig config = configMapper.checkConfigKeyUnique(configKey);
        if (config == null || config.getConfigValue() == null) {
            throw new RuntimeException("未找到有效配置: " + configKey);
        }

        // 4. 转换并返回
        try {
            return new BigDecimal(config.getConfigValue().trim());
        } catch (NumberFormatException e) {
            throw new RuntimeException("配置值格式错误: " + configKey, e);
        }
    }

    /**
     * 根据等级构建配置键
     */
    private String buildConfigKeyByLevel(int level) {
        switch (level) {
            case 1: return "workshop_level_1";
            case 2: return "workshop_level_2";
            default: throw new RuntimeException("无效车间等级: " + level);
        }
    }

    @Override
    public int register(GarageBo garageBo) {

        // 判断用户是否已经注册成为商家
        Long userId = SecurityUtils.getUserId();
        Garage garage1 = garageMapper.selectByUserId(userId);

        if (StringUtils.isNotNull(garage1) && garage1.getStatus() == 2) {
            throw new RuntimeException("你已经注册成为商家，请勿重复注册");
        }
        Garage garage = new Garage();
        BeanUtils.copyProperties(garageBo, garage);
        if (garageBo.getTransportLicenses() != null) {
            garage.setTransportLicense(String.join(",", garageBo.getTransportLicenses()));
        }
        if (garageBo.getShopPhotosList() != null && garageBo.getShopPhotosList().size() > 0) {
            garage.setShopPhotos(String.join(",", garageBo.getShopPhotosList()));
        }
        if (garageBo.getServiceTypeIdsArray() != null && garageBo.getServiceTypeIdsArray().length > 0) {
            garage.setServiceTypeIds(String.join(",", garageBo.getServiceTypeIdsArray()));
        }
        if (garageBo.getQualificationPhotosArray() != null) {
            garage.setQualificationPhotos(String.join(",", garageBo.getQualificationPhotosArray()));
        }
        if (garageBo.getServiceAreasList() != null && garageBo.getServiceAreasList().size() > 0) {
            garage.setServiceAreas(String.join(",", garageBo.getServiceAreasList()));
        }
        if (garageBo.getEnvironmentPhotosArray() != null && garageBo.getEnvironmentPhotosArray().length > 0) {
            garage.setEnvironmentPhotos(String.join(",", garageBo.getEnvironmentPhotosArray()));
        }

        garage.setUserId(userId);
        if (StringUtils.isNotNull(garage1) && garage1.getStatus() != 2) {
            garage.setId(garage1.getId());
            return garageMapper.updateGarage(garage);
        }
        return garageMapper.insertGarage(garage);
    }

    @Override
    public int receivingOrder(Integer receivingOrder) {
        Garage garage1 = garageMapper.selectByUserId(SecurityUtils.getUserId());
         if (garage1 == null){
            throw new RuntimeException("请先注册成为商家");
        }
        if ( garage1.getAuditStatus() != 2){
             throw new RuntimeException("只有待审核状态可以修改接单状态");
        }
        Garage garage = new Garage();
        garage.setReceivingOrder(receivingOrder);
        garage.setUpdateTime(DateUtils.getNowDate());
        garage.setUpdateBy(SecurityUtils.getUsername());
        garage.setUserId(SecurityUtils.getUserId());

        return garageMapper.updateGarageByUserId(garage);
    }


}
